package com.chuangke.admin.util;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.CollectionUtils;

import com.chuangke.admin.entity.SysDict;
import com.chuangke.admin.service.SysDictService;
import com.chuangke.common.exception.ChuangkeException;

import cn.hutool.core.util.StrUtil;

public class DictUtils {

	/**
	 * 自动增加字典数据，并给业务bean赋值上id
	 * 
	 * @param <T>
	 * @param sysDictService
	 * @param dataList
	 * @param dictType
	 * @param idColumn
	 * @param nameColumn
	 */
	public static <T> void autoHandleBeanAndSaveDict(SysDictService sysDictService, List<T> dataList, String dictType,
			String idColumn, String nameColumn) {
		DictUtils.autoHandleBeanAndSaveDict(sysDictService, dataList, dictType, null, idColumn, nameColumn);
	}
	
	public static synchronized <T> void autoHandleBeanAndSaveDict(SysDictService sysDictService, List<T> dataList, String dictType,
			String deptId, String idColumn, String nameColumn) {
		if(CollectionUtils.isEmpty(dataList)) {
			return ;
		}
		
		Map<String, SysDict> dictMap = null;
		if (StrUtil.isBlank(deptId)) {
			dictMap = sysDictService.findMap(dictType);
		} else {
			dictMap = sysDictService.findMap(dictType, deptId);
		}
		
		List<SysDict> dictList = dictMap.values().stream().collect(Collectors.groupingBy(SysDict::getName)).values().stream().map(g -> g.get(0)).collect(Collectors.toList()) ;
		Map<String, SysDict> nameDictMap = dictList.stream()
				.collect(Collectors.toMap(SysDict::getName, a -> a));
		int maxCode = sysDictService.getMaxIntegerCode(dictType);
		try {
			for (T data : dataList) {

				String id = BeanUtils.getProperty(data, idColumn);
				if (!StrUtil.isBlank(id)) {
					continue;
				}

				String name = BeanUtils.getProperty(data, nameColumn);
				name = StrUtil.isBlank(name) ? "" : name.replaceAll(" ", "");

				if (StrUtil.isBlank(name)) {
					continue;
				}

				SysDict dict = nameDictMap.get(name);
				if (dict != null) {
					BeanUtils.setProperty(data, idColumn, dict.getCode());
					continue;
				}

				SysDict sgxc = new SysDict();
				sgxc.setType(dictType);
				sgxc.setCode(++maxCode + "");
				sgxc.setName(name);
				if (!StrUtil.isBlank(deptId)) {
					sgxc.setDeptId(deptId);
				}

				sysDictService.autoSave(sgxc);

				BeanUtils.setProperty(data, idColumn, sgxc.getCode());
				nameDictMap.put(name, sgxc);
			}
		} catch (Exception e) {
			sysDictService.cacheEvict();
			throw new ChuangkeException(e);
		}
	}

	public static synchronized <T> void autoHandleBeanAndSaveDictById(SysDictService sysDictService, List<T> dataList, String dictType,
			String deptId, String idColumn) {
		if(CollectionUtils.isEmpty(dataList)) {
			return ;
		}
		
		Map<String, SysDict> dictMap = null;
		if (StrUtil.isBlank(deptId)) {
			dictMap = sysDictService.findMap(dictType);
		} else {
			dictMap = sysDictService.findMap(dictType, deptId);
		}
		
		List<SysDict> dictList = dictMap.values().stream().collect(Collectors.groupingBy(SysDict::getCode)).values().stream().map(g -> g.get(0)).collect(Collectors.toList()) ;
		Map<String, SysDict> codeDictMap = dictList.stream()
				.collect(Collectors.toMap(SysDict::getCode, a -> a));
		int maxCode = sysDictService.getMaxIntegerCode(dictType);
		try {
			for (T data : dataList) {

				String idValue = BeanUtils.getProperty(data, idColumn);
				if (StrUtil.isBlank(idValue)) {
					continue;
				}
				
				//["张三","122471","122470","122473","王五"]
				idValue = idValue.replaceAll("\"", "").replaceAll("\\[", "").replaceAll("\\]", "").replaceAll(" ", "") ;
				String[] ids = idValue.split(",") ;

				String[] newIds = new String[ids.length] ;
				for(int i=0; i<ids.length; i++) {
					SysDict dict = codeDictMap.get(ids[i]);
					if (dict != null) {
						newIds[i] = ids[i] ;
						continue;
					}

					SysDict sgxc = new SysDict();
					sgxc.setType(dictType);
					sgxc.setCode(++maxCode + "");
					sgxc.setName(ids[i]);
					if (!StrUtil.isBlank(deptId)) {
						sgxc.setDeptId(deptId);
					}

					sysDictService.autoSave(sgxc);
					newIds[i] = sgxc.getCode() ;
				}
				
				String newIdValue = "[\""+String.join("\",\"", newIds) + "\"]" ;
				BeanUtils.setProperty(data, idColumn, newIdValue);
			}
		} catch (Exception e) {
			sysDictService.cacheEvict();
			throw new ChuangkeException(e);
		}
	}
}
